package org.cloudfoundry.services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import argo.jdom.JdomParser;
import argo.jdom.JsonNode;
import argo.jdom.JsonRootNode;
/**
 * This class implementation was taken from : 
 * http://technoroy.blogspot.co.il/2011/07/vmware-cloud-foundry-developing-cloud.html
 * And expanded to suit our needs.
 */
public enum ServiceManager implements CloudFoundryServices {

	INSTANCE;

	private static final String NULL_STRING = "";

	public Object getInstance(int service_type) throws Exception {
		if (service_type == MYSQL) {
			return getMySQLConnection();
		} else {
			throw new IllegalArgumentException("Service for id " + service_type
					+ " not found...");
		}
	}

	/*
	 * This method is responsible for establishing a valid connection to the
	 * MySQL service, using the credentials available in the environment
	 * variable, namely "VCAP_SERVICES".
	 * 
	 * The content of VCAP_SERVICES environment variable is a JSON string, thus
	 * this method uses standard interfaces from the Argo JSON parsing API to
	 * extract the credentials.
	 */

	private Object getMySQLConnection() throws SQLException {
		String vcap_services = System.getenv("VCAP_SERVICES");

		String hostname = NULL_STRING;
		String dbname = NULL_STRING;
		String user = NULL_STRING;
		String password = NULL_STRING;
		String port = NULL_STRING;

		if (vcap_services != null && vcap_services.length() > 0) {
			try {
				JsonRootNode root = new JdomParser().parse(vcap_services);

				JsonNode mysqlNode = root.getNode("mysql-5.1");
				JsonNode credentials = mysqlNode.getNode(0).getNode(
						"credentials");

				dbname = credentials.getStringValue("name");
				hostname = credentials.getStringValue("hostname");
				user = credentials.getStringValue("user");
				password = credentials.getStringValue("password");
				port = credentials.getNumberValue("port");

				String dbUrl = "jdbc:mysql://" + hostname + ":" + port + "/"
						+ dbname;

				Class.forName("com.mysql.jdbc.Driver");
				Connection connection = DriverManager.getConnection(dbUrl,
						user, password);
				return connection;
			} catch (Exception e) {
				throw new SQLException(e);
			}
		}

		return null;
	}

	/*************** New Content *********************************************/

	public void RunGenerelQuery(String i_Query) {
		Connection connection = null;
		try {
			connection = (Connection) ServiceManager.INSTANCE
					.getInstance(CloudFoundryServices.MYSQL);
			Statement s = connection.createStatement();
			s.executeUpdate(i_Query);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				try {
					if (!connection.isClosed()) {
						connection.close();
					}
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
		}
	}

	public boolean DeleteFromDatabase(String i_Table, int i_Id) {
		boolean success = false;
		Connection connection = null;
		int rowsAffected = 0;
		try {
			connection = (Connection) ServiceManager.INSTANCE
					.getInstance(CloudFoundryServices.MYSQL);
			Statement s = connection.createStatement();
			String query = "DELETE FROM " + i_Table + " WHERE id=" + i_Id;
			rowsAffected = s.executeUpdate(query);
			if (rowsAffected == 1) {
				success = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				try {
					if (!connection.isClosed()) {
						connection.close();
					}
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
		}
		return success;
	}

	public boolean UpdateQuery(String i_UpdateString) {
		boolean success = false;
		Connection connection = null;
		int rowsAffected = 0;
		try {
			connection = (Connection) ServiceManager.INSTANCE
					.getInstance(CloudFoundryServices.MYSQL);
			Statement s = connection.createStatement();
			String query = i_UpdateString;
			rowsAffected = s.executeUpdate(query);
			if (rowsAffected == 1) {
				success = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				try {
					if (!connection.isClosed()) {
						connection.close();
					}
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
		}
		return success;
	}

	public int InsertQuery(String i_InsertString) {
		int result = -1;
		Connection connection = null;
		int rowsAffected = 0;
		try {
			connection = (Connection) ServiceManager.INSTANCE
					.getInstance(CloudFoundryServices.MYSQL);
			Statement s = connection.createStatement();
			String query = i_InsertString;
			rowsAffected = s.executeUpdate(query);
			if (rowsAffected == 1) {
				// ID is auto-increment, update ID of object in memory
				query = "select last_insert_id()";
				ResultSet rs = s.executeQuery(query);
				rs.first();
				result = rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = -1;
		} finally {
			if (connection != null)
				try {
					if (!connection.isClosed()) {
						connection.close();
					}
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
		}

		return result;
	}
}
